
package com.chengyu.eyc.config.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.chengyu.eyc.constant.EycConstants;

import cn.hutool.core.util.StrUtil;

/**
 * 校验码验证
 *
 */
public class EycLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String ERR_CODE = "errcode";

    private String servletPath;

    public EycLoginAuthenticationFilter(String servletPath) {
        super(servletPath); 
        String failureUrl =String.format("%s?error=true",servletPath);
        setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(failureUrl));
        this.servletPath=servletPath;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
        return null;
    }

    /* private String decryptParams(String param) {
        try {
            return AESUtils.decryptByDefaultKey(param);
        } catch (Exception e) {
            return param;
        }
    
    }*/

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
//        setInnerUserAuthenticationFailureUrl(request);
        HttpServletRequest req = (HttpServletRequest)request;
//        String username = req.getParameter("username");
//        if (StringUtils.isNotBlank(username)) {
//            String freezeKey = EbConstants.CacheKey.getPrefixlockUserIdKey(username);
//            if (RedisUtil.exists(freezeKey, false)) {
//                req.getSession().setAttribute(ERR_CODE, "004");
//                unsuccessfulAuthentication(req, (HttpServletResponse)response,
//                    new InsufficientAuthenticationException(String.format("[%s]账号已被系统锁定,请[%d小时]后再试,谢谢！", username,
//                        CustomAuthenticationFailureHandler.LOCK_ACCOUNTS_TIME / 3600L)));
//                return;
//            }
//        }
//        String password = req.getParameter("password");
//        if (StringUtils.isNotBlank(password)) {
//            password = this.decryptParams(password);
//            if (!EbUtils.isStrongPassword(password)) {
//                HttpServletResponse res = (HttpServletResponse)response;
//                req.getSession().setAttribute(ERR_CODE, "001");
//                unsuccessfulAuthentication(req, res, new InsufficientAuthenticationException("密码强度不够,请更正密码"));
//                return;
//            }
//            if (isWeakPassword(password)) {
//                req.getSession().setAttribute(ERR_CODE, "002");
//                unsuccessfulAuthentication(req, (HttpServletResponse)response,
//                    new InsufficientAuthenticationException(String.format("密码中请不要出现%s,这将会对您的账号安全带来极大的风险", password)));
//                return;
//            }
//            if (StringUtils.isNotBlank(username)) {
//                String prefixLetters = username.length() > 5 ? username.substring(0, 5) : username;
//                if (password.contains(prefixLetters)) {
//                    req.getSession().setAttribute(ERR_CODE, "003");
//                    unsuccessfulAuthentication(req, (HttpServletResponse)response,
//                        new InsufficientAuthenticationException(
//                            String.format("密码中请不要出现%s,这将会对您的账号安全带来极大的风险", prefixLetters)));
//                    return;
//                }
//            }
//        }
//        //内部员工登录 多校验一次手机验证码。
//        if (StringUtils.isNotBlank(username) && req.getParameter(EbConstants.USER_TYPE).equalsIgnoreCase(UserTypeEnums.INTERNAL_USER.getCde())) {
//           String phoneVerifyCode = req.getParameter("phoneVerifyCode");
//           if(StringUtil.isBlank(phoneVerifyCode)){
//               req.getSession().setAttribute(ERR_CODE, "phoneVerfiyCode Error");
//               unsuccessfulAuthentication(req, (HttpServletResponse)response,
//                       new InsufficientAuthenticationException("请输入手机验证码!"));
//               return;
//           }
//            PhoneVerifyCdeSrchParams pvsp = new PhoneVerifyCdeSrchParams();
//            pvsp.setVerCode(phoneVerifyCode);
//            pvsp.setSmsSource("InnerUserLogin");
//            pvsp.setUserId(username);
//            EbUserServiceClient ebUserServiceClient = SpringContextHelper.getBean(EbUserServiceClient.class);
//            try {
//                ebUserServiceClient.checkSysUserPhoneVerifyCde(pvsp).getData();
//            } catch (GenericException e) {
//                req.getSession().setAttribute(ERR_CODE, "phoneVerfiyCode Error");
//                unsuccessfulAuthentication(req, (HttpServletResponse) response,
//                        new InsufficientAuthenticationException(e.getMessage()));
//                return;
//            }
//        }
        if (hasError(req)) {
            HttpServletResponse res = (HttpServletResponse)response;
            if ("POST".equalsIgnoreCase(req.getMethod()) && StrUtil.equals(servletPath, req.getServletPath())) {
                String expect = (String)req.getSession().getAttribute(EycConstants.VERIFY_CODE);
                if (StrUtil.isNotBlank(expect)
                    && !expect.equalsIgnoreCase(req.getParameter(EycConstants.VERIFY_CODE))) {
                    req.getSession().setAttribute(ERR_CODE, "005");
                    unsuccessfulAuthentication(req, res, new InsufficientAuthenticationException("输入的图形验证码不正确"));
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }

    private boolean hasError(HttpServletRequest request) {
        Object message = request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        return message != null;
    }

//    private boolean isWeakPassword(String password) {
//        EbUserServiceClient userServiceClient = SpringContextHelper.getBean(EbUserServiceClient.class);
//        ResponseResult<Boolean> res = userServiceClient.isWeakPassword(password);
//        return res != null && res.getData() != null && res.getData();
//    }
//
//    /**
//     * @param request
//     */
//    private void setInnerUserAuthenticationFailureUrl(ServletRequest request) {
//        if (StringUtil.equals(request.getParameter(EbConstants.USER_TYPE), UserTypeEnums.INTERNAL_USER.getCde())) {
//            setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(
//                String.format("%s%s", WebSecurityConfig.INNER_USER_LOGIN, "?error")));
//        } else {
//            setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(
//                String.format("%s%s", WebSecurityConfig.LOGIN_URL, "?error")));
//        }
//    }

}
